<template>
  <div class="mobile-video-page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="left-section">
        <div class="logo">
          <img src="../../../../assets/images/logo.png" alt="logo" class="logo">
        </div>
        <div class="title-container">
          <div class="title">西大数信数帮学堂</div>
          <div class="sub-title">广西大学数学与信息科学学院</div>
        </div>
      </div>
      <div class="search-box">
        <div class="search-input">
          <div class="search-wrapper">
            <el-icon class="search-icon"><Search /></el-icon>
            <input
                type="text"
                placeholder="输入关键词搜索"
                v-model="keyword"
                @keyup.enter="handleSearch"
            />
          </div>
        </div>
      </div>
      <div class="home-btn">
        <button class="home-button" @click="goHome">
          首页
          <el-icon class="home-icon"><HomeFilled /></el-icon>
        </button>
      </div>
    </header>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <!-- 排序方式 -->
      <div class="filter-row">
        <button
            v-for="item in sortOptions"
            :key="item.value"
            :class="['filter-btn', { active: currentSort === item.value }]"
            @click="handleFilterClick('sort', item.value)"
        >
          {{ item.label }}
        </button>
      </div>

      <!-- 日期筛选 -->
      <div class="filter-row">
        <button
            v-for="item in dateOptions"
            :key="item.value"
            :class="['filter-btn', { active: currentDate === item.value }]"
            @click="handleFilterClick('date', item.value)"
        >
          {{ item.label }}
        </button>
      </div>

      <!-- 时长筛选 -->
      <div class="filter-row">
        <button
            v-for="item in durationOptions"
            :key="item.value"
            :class="['filter-btn', { active: currentDuration === item.value }]"
            @click="handleFilterClick('duration', item.value)"
        >
          {{ item.label }}
        </button>

      </div>

      <!-- 分区筛选 -->
      <div class="filter-row">
        <button
            v-for="item in categoryOptions"
            :key="item.value"
            :class="['filter-btn', { active: currentCategory === item.value }]"
            @click="handleFilterClick('category', item.value)"
        >
          {{ item.label }}
        </button>
      </div>
    </div>
    <!-- 视频列表 -->
    <div class="content-section" v-if="page">
      <div class="rank-grid">
        <div
            v-for="(item, index) in page.records"
            :key="index"
            class="rank-card"
            @click="goToVideo(item)"
        >
          <div class="video-cover">
            <img :src="getImageUrl(item.bannerId)" :alt="item.title" loading="lazy">
            <div class="video-duration">{{ displayDuration(item?.duration ?? 0*1000) }}</div>
            <div class="play-icon">▶</div>
          </div>
          <div class="video-info">
            <!--            <p class="video-title">{{ item.title }}</p>-->
            <div class="video-title maxline-2" :title="item.title" v-html="item.highlightTitle||item.title"></div>
            <div class="video-meta">
              <span><el-icon><VideoPlay /></el-icon>{{ item.plays }}</span>
              <!--              <span><el-icon><ChatDotRound /></el-icon>{{ item.commentCount }}</span>-->
            </div>
            <div class="author-info">
              <img :src="getImageUrl(item.user.avatarId)" :alt="item.user.nickname" class="avatar">
              <span class="author-name">{{ item.user.nickname }}</span>
              <span class="publish-date">{{ item.dynamic.publishTimeStr  }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div ref="loadMoreTrigger" class="loading-container">
        <div v-if="isLoadingMore" class="loading-spinner">
          <div class="spinner"></div>
          <span>>加载中...</span>
        </div>
        <div v-else-if="!hasMoreData" class="no-more-data">
          没有更多记录了
        </div>
    </div>
    
  </div>
</template>

<script setup lang="ts">
import router from '@/router'
import { ref, onMounted, watch } from 'vue'
import { searchAll } from '@/apis/search';
import videoSearchApi from "@/apis/video/search";
import {usePage} from "@/hooks/usePage.ts";
import videoApi from "@/apis/video";
import {pick} from "lodash";
import { imageUrl } from '@/apis/image';
import {displayDuration} from "@/utils/common.ts";
import {VideoPlay} from "@element-plus/icons-vue";
const isLoadingMore = ref(false)
const hasMoreData = ref(true)
let observer: IntersectionObserver | null = null

// 获取图片URL
function getImageUrl(bannerId: string) {
  // 根据您的实际API调整图片URL构造方式
  // return `/api/resource/${bannerId}`
  return imageUrl + bannerId
}


// 日期选项
const dateOptions = [
  { label: '全部日期', value: '' },
  { label: '最近一天', value: 'DAY' },
  { label: '最近一周', value: 'WEEK' },
  { label: '最近一月', value: 'MONTH' },
  { label: '最近半年', value: 'HALF_YEAR' }
]




const goHome = () => {
  router.push('/mobile')
}

// 添加时间记录
const courseTimes = ref<Record<string, number>>({})

//点击视频
const  goToVideo = (value: object) => {

  const url = generateVideoUrl(value)
  // 使用 Vue Router 在当前页面跳转
  router.push(url)
}
// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/mobile/play/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0

  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}

//搜索关键词
const keyword = useRouteQuery('kw', '')
// const sort = useRouteQuery<string>('sort', '')
const sortParam = useRouteQuery<string>('sort', 'SCORE') // 默认值改为 SCORE
// console.log('keyword:路由值为', sort.value)
// const currentSort = ref(sort.value || 'SCORE')
const currentSort = ref(sortParam.value)
// console.log('currentSort:路由值为', currentSort.value)

// 监听路由参数变化，同步到组件状态
watch(sortParam, (newVal) => {
  currentSort.value = newVal
})

const pageSize = 9
const pageNum = useRouteQuery('page', 1)
const route = useRoute()
const { state: options } = useAsyncState(videoSearchApi.getOptions(), [])
const { page, loading, run, error } = usePage(search)
function search(pageNum: number) {
  return videoApi.search({
    type: 'VIDEO',
    keyword: keyword.value,
    pageNum,
    pageSize: 9,
    sort: currentSort.value,
    date: currentDate.value,
    duration: currentDuration.value,
    channelId: currentCategory.value,
    ...pick(route.query, options.value.map(a=>a.query))
  })
}

// 处理筛选点击事件
const handleFilterClick = async(type: string, value: string) => {
  // 更新对应的响应式变量
  // console.log('点击筛选:', type, value)
  switch(type) {
    case 'sort':
      currentSort.value = value;
      // 更新 URL 查询参数
      // router.replace({
      //   query: {
      //     ...route.query,
      //     sort: value
      //   }
      // })
      // const newQuery = { ...route.query }
      // newQuery[type] = value
      //  // 如果值为空字符串或者默认值，可以考虑删除该参数
      // if (value === '' || (type === 'sort' && value === 'SCORE')) {
      //   delete newQuery[type]
      // }
      // router.replace({
      //   query: newQuery
      // })
      break;
    case 'date':
      currentDate.value = value;
      break;
    case 'duration':
      currentDuration.value = value;
      break;
    case 'category':
      currentCategory.value = value;
      break;
  }
   // 统一更新 URL 查询参数
  const newQuery = { ...route.query }
  newQuery[type] = value
  // 如果值为空字符串或者默认值，可以考虑删除该参数
  if (value === '' || (type === 'sort' && value === 'SCORE')) {
    delete newQuery[type]
  }
  await router.replace({
    query: newQuery
  })
  // 等待 DOM 更新后执行搜索
  //await nextTick();
  // 触发搜索
  handleSearch();
};




// 定义一个方法来根据 query 属性获取对应的选项数组
function getOptionsByQuery(query: string) {
  const optionItem = options.value.find(item => item.query === query);
  return optionItem ? optionItem.options : [];
}

// 分组后的4个数组数据
const sortOptions = computed(() => getOptionsByQuery('sort'));        // 排序选项数组


//const dateOptions = computed(() => getOptionsByQuery('date'));        // 日期选项数组
const currentDate = ref('')

const durationOptions = computed(() => getOptionsByQuery('duration')); // 时长选项数组
const currentDuration = ref('ALL')

const categoryOptions =  computed(() => getOptionsByQuery('channelId')); // 分区选项数组
const currentCategory = ref('')






watchImmediate(()=>route.query, ()=>{
  run(pageNum.value)
})

// 添加搜索处理函数
const handleSearch = () => {
  // 重置页码到第一页
  pageNum.value = 1
  // 执行搜索
  run(1)
}

const loadMore = async () => {
  if (isLoadingMore.value || !hasMoreData.value) return;
  
  isLoadingMore.value = true;
  try {
    const nextPageNum = pageNum.value ? pageNum.value + 1 : 1;
    const result = await search(nextPageNum);
    const currentPage = unref(page)
    if (result.records && result.records.length > 0) {
       setTimeout(() => {
        page.value.records = [...(page.value.records || []), ...result.records];
        hasMoreData.value = result.current < result.pages;
      }, 1500); 
    } else {
      hasMoreData.value = false;
    }
  } catch (error) {
    console.error('Error loading more videos:', error);
  } finally {
    isLoadingMore.value = false;
  }
};

const setupInfiniteScroll = () => {
  const loadMoreTrigger = document.querySelector('.loading-container');
  if (!loadMoreTrigger) return;
  
  observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting && hasMoreData.value) {
      loadMore();
    }
  }, {
    rootMargin: '100px' // Load 100px before reaching the end
  });
  
  observer.observe(loadMoreTrigger);
};

onBeforeUnmount(() => {
  if (observer) {
    observer.disconnect();
  }
});

// Initialize infinite scroll after component is mounted
onMounted(() => {
  setupInfiniteScroll();
});



</script>

<style scoped lang="scss">
.mobile-video-page {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  -webkit-tap-highlight-color: transparent;
  overflow-x: hidden;
  width: 100%;
  background-color: #f5f5f5;
  height: calc(100vh - 90px);
  // max-height: calc(100vh - 90px);
  // padding-bottom: 110px;
  // position: relative;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏样式 */
.header {
  display: flex;
  align-items: center;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)),
  url('@/assets/1sz3p8w2Sk.png@3840w_400h_1c.webp');
  background-size: cover;
  background-position: center;
  backdrop-filter: blur(2px);
  padding: 8px 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 999;
  gap: 8px;
  width: 100%;
  box-sizing: border-box;

  .left-section {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 10px;
    min-width: 0;
  }

  .logo {
    flex-shrink: 0;

    img {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      object-fit: cover;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }
  }

  .title-container {
    flex: 1;
    min-width: 0;
  }

  .title {
    font-size: 15px;
    font-weight: 600;
    line-height: 1.3;
    color: #1a1a1a;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 2px;
  }

  .sub-title {
    font-size: 11px;
    color: #666;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .search-box {
    flex: 1.2;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .search-input {
    width: 100%;
    max-width: 200px;
  }

  .search-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 18px;
    padding: 6px 14px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;

    &:focus-within {
      background-color: #ffffff;
      box-shadow: 0 3px 10px rgba(0, 0, 0, 0.12);
    }

    input {
      flex: 1;
      border: none;
      outline: none;
      background: transparent;
      font-size: 13px;
      color: #333;
      padding: 0;

      &::placeholder {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .search-icon {
    font-size: 16px;
    color: #999;
    margin-right: 8px;
    flex-shrink: 0;
  }

  .home-btn {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .home-button {
    background: rgba(255, 255, 255, 0.95);
    border: none;
    border-radius: 18px;
    padding: 6px 14px;
    font-size: 13px;
    font-weight: 500;
    color: #333;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    display: flex;
    align-items: center;
    gap: 4px;
    white-space: nowrap;
    -webkit-tap-highlight-color: transparent;
    user-select: none;

    .home-icon {
      font-size: 14px;
    }

    &:hover {
      background: #ffffff;
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
      transform: translateY(-1px);
    }
  }
}

/* 筛选区域样式 */
.filter-section {
  background: #ffffff;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  .filter-row {
    display: flex;
    flex-wrap: wrap; // 允许换行
    gap: 8px;
    margin-bottom: 10px;
    // 移除 overflow-x 和滚动条隐藏相关样式
    &:last-child {
      margin-bottom: 0;
    }
  }


  .filter-btn {
    flex-shrink: 1; // 允许按钮收缩
    padding: 6px 16px;
    background: #f0f0f0;
    border: none;
    border-radius: 16px;
    font-size: 13px;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    min-width: fit-content; // 确保按钮内容完整显示

    &.active {
      background: linear-gradient(135deg, #00d4ff 0%, #0099ff 100%);
      color: #ffffff;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0, 153, 255, 0.3);
    }

    &:hover:not(.active) {
      background: #e5e5e5;
    }
  }

}

/* 视频列表样式 */
.video-list {
  padding: 12px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  background: #f5f5f5;

  .video-item {
    background: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    cursor: pointer;
    transition: all 0.3s ease;
    -webkit-tap-highlight-color: transparent;
    user-select: none;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    }
  }

  .video-cover {
    position: relative;
    width: 100%;
    padding-top: 56.25%; /* 16:9 比例 */
    overflow: hidden;
    background: #e0e0e0;

    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .episode-badge {
      position: absolute;
      bottom: 6px;
      right: 6px;
      background: rgba(0, 0, 0, 0.75);
      color: #ffffff;
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 11px;
      font-weight: 500;
    }
  }

  .video-title {
    padding: 10px;
    font-size: 13px;
    color: #333;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .video-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
  }
}

@media (max-width: 480px) {
  .header {
    padding: 6px 8px;
    gap: 6px;

    .logo img {
      width: 32px;
      height: 32px;
    }

    .title {
      font-size: 13px;
    }

    .sub-title {
      font-size: 9px;
    }

    .search-input {
      max-width: 140px;
    }

    .search-wrapper {
      padding: 5px 12px;

      input {
        font-size: 11px;
      }
    }

    .home-button {
      padding: 5px 12px;
      font-size: 11px;
    }
  }

  .filter-section {
    padding: 10px;

    .filter-row {
      gap: 6px;
      margin-bottom: 8px;
    }

    .filter-btn {
      padding: 5px 12px;
      font-size: 12px;
    }
  }

  .video-list {
    .video-title {
      font-size: 12px;
      padding: 8px;
    }

    .episode-badge {
      font-size: 10px;
      padding: 2px 6px;
    }
  }

  .footer {
    font-size: 10px;
    padding: 15px 10px;
  }
}
// 热力排行
.rank-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  width: 100%;

  .rank-card {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    width: 100%;
    max-width: 100%;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .video-cover {
      position: relative;
      width: 100%;
      padding-bottom: 56.25%;
      overflow: hidden;
      background-color: #f0f0f0;

      img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .video-duration {
        position: absolute;
        bottom: 6px;
        right: 6px;
        background-color: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 11px;
        z-index: 2;
      }

      .play-icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        color: #fff;
        font-size: 14px;
        opacity: 0;
        transition: opacity 0.3s ease;
      }

      &:hover .play-icon {
        opacity: 1;
      }
    }

    .video-info {
      padding: 8px;

      .video-title {
        font-size: 12px;
        line-height: 1.4;
        color: #333;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .video-meta {
        display: flex;
        gap: 12px;
        font-size: 11px;
        color: #999;
        margin-bottom: 8px;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }

      .author-info {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 11px;
        color: #666;

        .avatar {
          width: 16px;
          height: 16px;
          border-radius: 50%;
        }

        .author-name {
          flex: 1;
        }

        .publish-date {
          color: #999;
        }
      }
    }
  }
}
.content-section{
  // height: 55vh;
  flex-grow: 1;
  overflow-y: auto; 
}
.loading-container {
  display: flex;
  justify-content: center;
  // padding: 5px;
  
  .loading-spinner {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    
    .spinner {
      width: 24px;
      height: 24px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #0099ff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  }
  
  .no-more-data {
    color: #999;
    font-size: 14px;
    padding: 10px;
  }
}
</style>

